<template>
  <Dialog :appDialog="appDialog">
    <div class="depart_box">
      <div class="depart_l">
        <el-input v-model="searchName" class="search_name" placeholder="搜索成员、部门" :prefix-icon="Search" :filter-node-method="filterNode" />
        <el-button v-if="isExternal" style="margin-left: 20px" type="text" @click="getDepartList">刷新页面</el-button>
        <el-scrollbar height="400px">
          <el-tree ref="treeRef" :data="depart" node-key="id" :props="defaultProps" default-expand-all :filter-node-method="filterNode">
            <template #default="{ node, data }">
              <span class="custom-tree-node" v-if="isMember">
                <el-tooltip effect="dark" content="该员工需要先前往企业微信授权" placement="top-start" v-if="data.type == 'user' && !data.authorized && isDisableType == 1">
                  <el-checkbox v-model="data.check" :disabled="data.is_sub_account" class="depart_member" @change="currentChange(data, node)">
                    <span>
                      <el-icon class="depart_member_icon">
                        <user-filled />
                      </el-icon>
                      <span>{{ node.label }}</span>
                    </span>
                  </el-checkbox>
                </el-tooltip>
                <span v-else>
                  <el-checkbox v-if="data.type == 'user'" v-model="data.check" :disabled="data.disabled || data.is_sub_account || (isNotWxUser && data.is_wx_follow_user == 0)" class="depart_member" @change="currentChange(data, node)">
                    <span>
                      <el-icon class="depart_member_icon">
                        <user-filled />
                      </el-icon>
                      <span>{{ node.label }}</span>
                    </span>
                  </el-checkbox>
                  <span v-else>
                    <img class="depart_icon" src="/static/newDepart.png" alt="" />
                    {{ node.label }}（{{ data.members || 0 }}）
                  </span>
                </span>
              </span>
              <span v-else class="custom-tree-node">
                <el-tooltip effect="dark" content="该员工需要先前往企业微信授权" placement="top-start" v-if="data.type == 'user' && !data.authorized && isDisableType == '1'">
                  <el-checkbox v-model="data.check" class="depart_member" :disabled="data.is_sub_account" @change="currentChange(data, node)">
                    <span>
                      <el-icon class="depart_member_icon">
                        <user-filled />
                      </el-icon>
                      <span>{{ node.label }}</span>
                    </span>
                  </el-checkbox>
                </el-tooltip>
                <span v-else>
                  <el-checkbox v-model="data.check" class="depart_member" :disabled="data.disabled" @change="currentChange(data, node)">
                    <span>
                      <el-icon v-if="data.type == 'user'" class="depart_member_icon">
                        <user-filled />
                      </el-icon>
                      <img v-else class="depart_icon mr2" src="/static/depart.png" alt="" />
                      <span>{{ node.label }}</span>
                      <span>{{ data.type == 'user' ? '' : `（${data.members || 0}）` }}</span>
                    </span>
                  </el-checkbox>
                </span>
              </span>
            </template>
          </el-tree>
        </el-scrollbar>
      </div>
      <div class="depart_r">
        <div class="depart_select_title">已选择的员工</div>
        <el-scrollbar height="400px">
          <div class="seled_member" v-for="item in selectedMember" :key="item.id">
            <div class="item_member">
              <el-icon v-if="item.type == 'user'" class="seled_icon">
                <user-filled />
              </el-icon>
              <img v-else class="depart_icon" src="/static/depart.png" alt="" />
              <span class="member_name">{{ item.name }}</span>
            </div>
            <el-icon @click="removeItem(item)" class="remove_icon">
              <close />
            </el-icon>
          </div>
        </el-scrollbar>
      </div>
    </div>
  </Dialog>
</template>
<script lang="ts" setup>
  import { ref, reactive, watch, watchEffect, computed } from 'vue'
  import Dialog from '@/components/Dialog.vue'
  import { Search, UserFilled } from '@element-plus/icons-vue'
  import type { ElTree } from 'element-plus'
  import { getDepartUser } from '@/api/common'
  import { useStore } from '@/store'
  import { getSetionId } from '@/utils/utils'
  const emit = defineEmits(['submit', 'determine'])
  const store = useStore()
  const treeRef = ref<InstanceType<typeof ElTree>>()

  const props = defineProps({
    type: Number
  })

  interface Tree {
    id: number
    label: string
    children?: Tree[]
  }
  interface Depart {
    departVisble: boolean
    title?: string
    creaters?: any[]
    isMember?: boolean
  }
  // 部门信息
  // const departInfo = computed(() => {
  //   return store.getters['content/depart']
  // })
  // 选中人员新】
  const selectedMember = ref([])
  const limit = ref('1') //1为员工数据源 2 为开启会话存档和联系人权限的员工数据源
  const newSelect = ref([])
  const mobile = ref('')
  const disabledSelected = ref([]) // 禁用成员
  const isDisableType = ref()
  // 弹框
  const departVisble = ref(false)
  // 是否只支持人员信息
  const isMember = ref(true)
  // 是否只支持人员信息
  const title = ref('部门人员信息')
  const multiple = ref(true) //多选
  const isExternal = ref(false) // 外部联系人
  const isNotWxUser = ref(false) //是否绑定企微员工
  const currentData = ref([])
  let employeeData = reactive({})
  const type = computed(() => {
    return store.getters['content/type']
  })
  watch(
    () => props.type,
    (val) => {
      isDisableType.value = val
    },
    { deep: true, immediate: true }
  )
  // const isDisableType = computed(() => {
  //   console.log(props.type, "类型")
  //   return props?.type;
  // })
  // watch(departInfo, (data) => {
  //   title.value = data.title
  //   isMember.value = data.isMember
  //   departVisble.value = data.departVisble
  //   selectedMember.value = data.creaters
  // })
  // 取消
  const cancelHandel = () => {
    // store.dispatch('content/depart', {
    //   isMember: true,
    //   departVisble: false
    // })
    // selectedMember.value = []
    const ids = getSetionId('id', newSelect.value)
    selectedMember.value = selectedMember.value.filter((item: any) => !ids.includes(item.id))
    departVisble.value = false
    isMember.value = true
    disabledSelected.value = []
    emit('submit', selectedMember.value)
  }
  //确定
  const submitHandel = () => {
    // store.dispatch('content/depart', {
    //   creaters: selectedMember
    // })
    newSelect.value = []
    // emit('submit', selectedMember.value)
    emit('determine', selectedMember.value)
    // departVisble.value = false
    disabledSelected.value = []
    isMember.value = true
  }
  const appDialog = reactive({
    visible: departVisble,
    title: title,
    width: '800px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })
  const searchName = ref('')
  const defaultProps = {
    children: 'children',
    label: 'name'
  }
  watch(searchName, (val) => {
    treeRef.value!.filter(val)
  })
  const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.name.indexOf(value) !== -1
  }

  // 部门左侧树
  const depart = ref([])
  // 获取部门员工信息
  watchEffect(() => {
    if (departVisble.value) {
      getDepartList()
    }
  })
  // 获取部门成员信息
  const getDepartList = async () => {
    // 部门ID department_id	1	Text	否
    // 外部联系人权限 is_wx_follow_user	默认 -1 全部 0 未开启 1 开启
    // 开启会话存档 is_open_session_archive	 默认 -1 全部 0 未开启 1 开启
    //根据手机号查询员工信息
    let params = {
      department_id: '',
      is_wx_follow_user: -1,
      is_open_session_archive: -1,
      mobile: '',
      has_authorization: 1
    }
    limit.value != '1' ? (params.is_open_session_archive = 1) : '' // 开启会话存档
    isExternal.value ? (params.is_wx_follow_user = 1) : '' //开启外部联系人
    params.mobile = mobile.value
    const data: any = await getDepartUser(params)
    const ids = getSetionId('id', selectedMember.value)
    depart.value = filterMember(data, ids)
  }
  // 过滤需要的人员信息
  const filterMember = (data: any, ids?: any[]) => {
    data = Array.isArray(data) ? data : [data]
    let arr: any[] = []
    data.forEach((item: any) => {
      item.disabled = disabledSelected.value.includes(item.id)
      if (multiple.value) {
        item.check = ids.includes(item.id)
      } else {
        const ids = getSetionId('id', selectedMember.value)
        item.check = ids.includes(item.id)
      }
      if (item.users && item.users.length > 0) {
        item.members = item.users.length
        if ((item.children && item.children.length == 0) || !item.children) {
          item.children = item.users
        } else {
          item.children = [...item.children, ...item.users]
        }
      }
      if (item.children && item.children.length > 0) {
        item.children = filterMember(item.children, ids)
      }

      checkRepeat(item)
      arr.push(item)
    })
    return arr
  }
  const current = ref()
  const currentChange = (data: Tree, node: any) => {
    if (isMember && data.type == 'user') {
      seletData(data)
    }
    if (data.type == 'department') {
      // data.children = childrenNode(data.check, data.children)
      // delete data.children
      // delete data.users
      seletData(data)
    }
    current.value = data
    if (data.check) {
      currentData.value.push(data.id)
      console.log(currentData.value)
    } else {
      const index = currentData.value.findIndex((v: any) => v === data.id)
      currentData.value.splice(index, 1)
    }
  }
  // 删除选中成员信息
  const removeItem = (data: any) => {
    let result = selectedMember.value.filter((item: any) => item.id != data.id)
    selectedMember.value = result
    depart.value = restoreDepart(data.id, depart.value)
    if (current.check) {
      currentData.value.push(current.id)
      console.log(currentData.value)
    } else {
      const index = currentData.value.findIndex((v: any) => v === data.id)
      currentData.value.splice(index, 1)
    }
  }
  // 选则部门后 后面成员全部选中
  // const childrenNode = (check: boolean, data: any[]) => {
  //   let arr: any[] = []
  //   if (data.length > 0) {
  //     data.forEach((item: any) => {
  //       item.check = check
  //       if (item.children && item.children.length > 0) {
  //         let children = childrenNode(check, item.children)
  //         item.children = children
  //       }
  //       arr.push(item)
  //     })
  //   }
  //   return arr
  // }
  // 选中后放在右边的数据
  const seletData = (item: any) => {
    // 多选
    if (multiple.value) {
      if (item.check) {
        selectedMember.value.push(item)
        newSelect.value.push(item)
      } else {
        if (selectedMember.value.length > 0) {
          selectedMember.value = selectedMember.value.filter((data: any) => item.id != data.id)
        }
      }
    } else {
      selectedMember.value = item.check ? [item] : []

      filterMember(depart.value)
    }
    // 递归查找相同员工
    checkRepeat(item)
  }
  // 递归查找相同员工，设置相同的check
  const checkRepeat = (item: any, data: Array<object> = depart.value) => {
    data.forEach((v: any) => {
      if (v.id === item.id) {
        v.check = item.check
      }
      if (v.children) {
        return checkRepeat(item, v.children)
      }
    })
  }

  //打开员工弹窗时，根据右边的数据确定左侧数的选中- val:true
  // 删除右侧选中成员 恢复左边
  const restoreDepart = (id: any, data: any, val?: any) => {
    let arr: any[] = []
    data.forEach((item: any) => {
      if (item.id === id) {
        item.check = val ? true : false
      } else {
        if (item.children && item.children.length > 0) {
          item.children = val ? restoreDepart(id, item.children, true) : restoreDepart(id, item.children)
        }
      }
      arr.push(item)
    })
    return arr
  }
  // 左侧树状态设置为false
  const clean = (data: any) => {
    let arr: any[] = []
    data.forEach((item: any) => {
      item.check = false
      if (item.children && item.children.length > 0) {
        item.children = clean(item.children)
      }
      arr.push(item)
    })
    return arr
  }
  const leftchecktree = (id?: any) => {
    depart.value = restoreDepart(id, depart.value, true)
  }
  // 查找部门的成员信息
  const restore = (data: any) => {
    let arr: any[] = []
    data.map((item: any) => {
      item.check = false
      if (item.children && item.children.length > 0) {
        item.children = restore(item.children)
      }
      arr.push(item)
    })
    return arr
  }
  defineExpose({
    departVisble,
    appDialog,
    title,
    leftchecktree,
    clean,
    depart,
    selectedMember,
    removeItem,
    isMember,
    disabledSelected,
    multiple,
    limit,
    mobile,
    isExternal,
    isNotWxUser,
    currentData,
    employeeData,
    searchName
  })
</script>
<style lang="scss" scoped>
  .depart_box {
    display: flex;
    .depart_member_icon {
      vertical-align: bottom;
      margin-right: 2px;
    }
    .depart_icon {
      width: 15px;
      vertical-align: middle;
    }
    .mr2 {
      margin-right: 2px;
    }
  }
  .depart_l {
    width: 350px;
    padding-right: 10px;
    border-right: 1px solid #eaeaea;
    .search_name {
      width: 259px;
      margin-bottom: 10px;
    }
    .custom-tree-node {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .is_member {
      // 不可全选样式
      :deep(.el-tree-node) {
        .is-leaf + .el-checkbox .el-checkbox__inner {
          display: inline-block;
        }
        .el-checkbox .el-checkbox__inner {
          display: none;
        }
      }
    }
  }
  .depart_r {
    padding: 10px 20px;
    flex: 1;
    .depart_select_title {
      margin-bottom: 20px;
    }
    .seled_member {
      line-height: 30px;
      display: flex;
      font-size: 14px;
      padding: 0 5px;
      align-items: center;
      justify-content: space-between;
      &:hover {
        background-color: rgba(255, 107, 0, 0.0901960784313725);
      }
      .item_member {
        display: flex;
        align-items: center;
        .seled_icon {
          color: #ff6b00;
        }
      }
      .member_name {
        margin-left: 2px;
      }
      .remove_icon {
        cursor: pointer;
        &:hover {
          transform: scale(1.23);
        }
      }
    }
  }
</style>
